package cn.lg.soar.core.util;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import cn.lg.soar.core.enums.LoggerLevelEnum;
import org.slf4j.LoggerFactory;

/**
 * 日志工具
 * @author luguoxiang
 * @date 2022/4/4
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public interface LoggerUtils {

    /**
     * 修改日志级别
     * @param name 日志名称
     * @param level 日志级别
     * @return 修改后的日志级别
     */
    static LoggerLevelEnum setLevel(String name, LoggerLevelEnum level) {
        Logger logger = (Logger)LoggerFactory.getLogger(name);
        Level l = Level.toLevel(level.name(), logger.getLevel());
        logger.setLevel(l);
        return getLevel(name);
    }

    /**
     * 获取日志级别
     * @param name 日志名称
     * @return 现在的日志级别
     */
    static LoggerLevelEnum getLevel(String name) {
        Logger logger = (Logger)LoggerFactory.getLogger(name);
        Level level = logger.getLevel();
        if (level == null) {
            level = logger.getEffectiveLevel();
        }
        return LoggerLevelEnum.valueOf(level.levelStr);
    }

    /**
     * 设置sql日志级别
     * @param level 日志级别
     */
    static void setSqlLogLevel(LoggerLevelEnum level) {
        setLevel("com.baomidou", level);
        setLevel("java.sql", level);
        setLevel("javax.sql", level);
    }

    /**
     * 开启sql日志
     */
    static void openSqlLog() {
        setSqlLogLevel(LoggerLevelEnum.INFO);
    }

    /**
     * 关闭sql日志
     */
    static void closeSqlLog() {
        setSqlLogLevel(LoggerLevelEnum.OFF);
    }

}
